package org.dy.db.support;

public class MySQLDialect implements Dialect {

    protected static final String SQL_END_DELIMITER = ";";
	public static final String RS_COLUMN = "nums";

    public String getLimitString(String sql, boolean hasOffset) {
        return new StringBuffer(sql.length() + 20).append(trim(sql)).append(
                hasOffset ? " limit ?,?" : " limit ?")
                .append(SQL_END_DELIMITER).toString();
    }

    public String getLimitString(String sql, int offset, int limit) {
        sql = trim(sql);
        StringBuffer sb = new StringBuffer(sql.length() + 20);
        
        int i=sql.indexOf("from");        
        sb.append(sql.subSequence(0, i));
        sb.append(",");
        sb.append(getCountSqlString(sql));
    	sb.append(sql.subSequence(i, sql.length()));
    	
        if (offset > 0) {
            sb.append(" limit ").append(offset).append(',').append(limit)
                    .append(SQL_END_DELIMITER);
        } else {
            sb.append(" limit ").append(limit).append(SQL_END_DELIMITER);
        }
        return sb.toString();
    }
    
    public String getCountSqlString(String sql){
        sql = trim(sql);
        StringBuffer sb = new StringBuffer(sql.length() + 10);
        if(sql.toLowerCase().startsWith("select")){
        	int i=sql.indexOf(" ");
        	int j=sql.lastIndexOf("from");
        	
        	sb.append("(");
        	sb.append(sql.subSequence(0, i));
        	sb.append(" ");
        	sb.append("count(*) ");
        	sb.append(sql.subSequence(j, sql.length()));
        	sb.append(") ");
        	sb.append(" as ");
        	sb.append(RS_COLUMN);
        	sb.append(" ");
        }
        return sb.toString();
    }
    
    public boolean supportsLimit() {
        return true;
    }

    private String trim(String sql) {
        sql = sql.trim();
        if (sql.endsWith(SQL_END_DELIMITER)) {
            sql = sql.substring(0, sql.length() - 1
                    - SQL_END_DELIMITER.length());
        }
        return sql;
    }

}